package be.ad.coffeebreak.web.commands;

import be.ad.coffeebreak.domain.ProjectHours;
import be.ad.coffeebreak.domain.User;
import be.ad.coffeebreak.services.ProjectHoursService;
import be.ad.coffeebreak.services.ProjectsService;
import be.ad.coffeebreak.web.Command;
import be.ad.coffeebreak.web.ServiceLocator;
import be.ad.coffeebreak.web.WebConstants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Stefan Bangels
 */
public final class ProjectHoursCommand implements Command {

    protected ServiceLocator serviceLocator;

    public ProjectHoursCommand(ServiceLocator serviceLocator) {
        this.serviceLocator = serviceLocator;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user = (User) request.getAttribute(WebConstants.ATTRIBUTE_USER);
        Long projectId = Long.parseLong(request.getParameter("projectId"));
        String dateString = request.getParameter("date");
        Date date;
        try {
            date = new SimpleDateFormat("yyyyMMdd").parse(dateString);
        } catch (ParseException e) {
            return null;
        }
        ProjectHoursService projectHoursService = serviceLocator.getProjectHoursService();
        ProjectHours projectHours = projectHoursService.findProjectHours(projectId, date);
        if (projectHours == null) {
            projectHours = new ProjectHours();
        }
        request.setAttribute(WebConstants.ATTRIBUTE_PROJECT_HOURS, projectHours);
        return WebConstants.VIEW_PROJECT_HOURS;
    }

}
